package com.lambkit.core;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Pair;

import java.util.*;

/**
 * @author yangyong(孤竹行)
 */
public class Attr extends BaseAttr<Attr> {

    public static Attr create() {
        return new Attr();
    }

    public static Attr of(Map<String, Object> map) {
        Attr attribute = create();
        attribute.putAll(map);
        return attribute;
    }

    public static Attr by(String key, Object value)  {
        Attr attribute = create();
        attribute.set(key, value);
        return attribute;
    }

    /**
     * 将PO对象转为Dict
     *
     * @param <T>  Bean类型
     * @param bean Bean对象
     * @return Vo
     */
    public static <T> Attr parse(T bean) {
        return create().parseBean(bean);
    }

    /**
     * 根据给定的Pair数组创建Dict对象
     *
     * @param pairs 键值对
     * @return Attr
     * @since 5.4.1
     */
    @SafeVarargs
    public static Attr of(Pair<String, Object>... pairs) {
        final Attr dict = create();
        for (Pair<String, Object> pair : pairs) {
            dict.put(pair.getKey(), pair.getValue());
        }
        return dict;
    }

    /**
     * 根据给定的键值对数组创建Dict对象，传入参数必须为key,value,key,value...
     *
     * <p>奇数参数必须为key，key最后会转换为String类型。</p>
     * <p>偶数参数必须为value，可以为任意类型。</p>
     *
     * <pre>
     * Attr dict = Attr.of(
     * 	"RED", "#FF0000",
     * 	"GREEN", "#00FF00",
     * 	"BLUE", "#0000FF"
     * );
     * </pre>
     *
     * @param keysAndValues 键值对列表，必须奇数参数为key，偶数参数为value
     * @return Attr
     * @since 5.4.1
     */
    public static Attr of(Object... keysAndValues) {
        final Attr dict = create();

        String key = null;
        for (int i = 0; i < keysAndValues.length; i++) {
            if (i % 2 == 0) {
                key = Convert.toStr(keysAndValues[i]);
            } else {
                dict.put(key, keysAndValues[i]);
            }
        }

        return dict;
    }

    public String[] getAttrNames() {
        Set<String> attrNameSet = this.keySet();
        return (String[])attrNameSet.toArray(new String[attrNameSet.size()]);
    }

    public Object[] getAttrValues() {
        Collection<Object> attrValueCollection = this.values();
        return attrValueCollection.toArray(new Object[attrValueCollection.size()]);
    }
}
